package com.gxy.learn.securityauth.auth;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxy.learn.securityauth.entity.SysUser;
import com.gxy.learn.securityauth.jwt.JwtUser;
import com.gxy.learn.securityauth.mapper.SysUserMapper;
import com.gxy.learn.securityauth.mapper.SysUserRoleMapper;
import com.gxy.learn.securityauth.vo.SysUserRoleVO;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Description(自定义UserDetailsService)
 * @author: Gao xueyong
 * Create at: 2021/12/1 下午10:08
 */
@Service
public class SecurityUserDetailsService implements UserDetailsService {
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(SysUser::getLoginName,userName);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if(null == sysUser){
            throw new UsernameNotFoundException("用户不存在！");
        }
        List<SysUserRoleVO> userRoles = sysUserRoleMapper.getSysRoleListByUserId(sysUser.getId());
        String roleNames = userRoles.stream().map(SysUserRoleVO::getEnname).collect(Collectors.joining(","));
        /**
         * 如果在控制器使用 @hasRole权限验证 则需要再写入权限时 添加ROLE_前缀
         */
//        return new JwtUser("admin", new BCryptPasswordEncoder().encode("123456"), AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_user"));
        return new JwtUser(sysUser.getLoginName(), new BCryptPasswordEncoder().encode(sysUser.getPassword()), AuthorityUtils.commaSeparatedStringToAuthorityList(roleNames));
    }
}
